package com.syyo.admin.service.impl;

import com.syyo.admin.service.FileService;
import com.syyo.common.constant.SettingsConstant;
import com.syyo.common.domain.FileUpload;
import com.syyo.common.utils.MyFileUtil;
import com.syyo.common.utils.MyurlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Auther: wangzhong
 * @Date: 2020/8/18 10:17
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private SettingsConstant settingsConstant;

    @Override
    public FileUpload uploadFile(MultipartFile file) {
        FileUpload fileUpdate = new FileUpload();
        // 获取文件名称
        String encoderFilename = file.getOriginalFilename();

        // 计算文件大小
        long fileS = file.getSize();
        String fileSizeString = MyFileUtil.FormetFileSize(fileS);

        //url解码
        String decoderFilename = MyurlUtils.getURLDecoderString(encoderFilename);

        // 文件后缀名
        //判断文件类型，获取不同的文件存储路径
        String filePath = isFileType(decoderFilename);
        String suffix = decoderFilename.substring(decoderFilename.lastIndexOf("."));
        //uuid去除中间的 '-'
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileFullName = filePath + uuid + suffix;
        File dest = new File(fileFullName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        fileUpdate.setFileName(decoderFilename);
        fileUpdate.setUrl(fileFullName);
        fileUpdate.setFileSize(fileSizeString);
        return fileUpdate;
    }

    /**
     * 判断文件类型 ,1：图片，2：文档，3：音乐，4：视频，5：其他
     *
     * @param fileName
     * @return
     */
    private String isFileType(String fileName) {
        int fileType = MyFileUtil.getFileType(fileName);
        switch (fileType) {
            case 1:
                return settingsConstant.getImagePath();
            case 2:
                return settingsConstant.getDocumentsPath();
            case 3:
                return settingsConstant.getMusicPath();
            case 4:
                return settingsConstant.getVideoPath();
            default:
                return settingsConstant.getOtherPath();
        }
    }
}
